"""
for 和C语言的for类似，但是有些许不同
"""

def testFor():
    # for
    words = ["cat", "window", "defense"]
    wordLength = 0

    for word in words:
        wordLength += len(word)

    print("all word length is {}".format(wordLength))

    # 如果在遍历序列的时候，想要修改序列，建议复制一份
    # 迭代的时候不会隐式copy，需要自己手动
    # 如果不复制的话，容易造成死循环
    for word in words[:]:
        if len(word) > 5:
            words.append(word)
        
    print("words is {}".format(words))

    # 如果需要迭代数字，可以使用range内置函数
    num = []
    for i in range(5):
        num.append(i)
    print("use range in for to generate some num, is {}".format(num))


    # 如果想通过索引来遍历，可以使用range()和len()
    money = [12, 23, 45, 56]
    concatedStr = ""

    for index in range(len(money)):
        concatedStr += str(money[index]) + " "
    print("concatedStr is {}".format(concatedStr))

    # 遍历字典的时候，我们可以同时获得key和value，但是需要使用字典的item方法
    fruits = {'apple': 'red', 'banana':'yellow', 'grape':'green'}
    fruitsName = []
    fruitsColor = []
    for key, value in fruits.items():
        fruitsName.append(key)
        fruitsColor.append(value)
    
    print("name of fruits is {0} and color is {1}".format(fruitsName, fruitsColor))

    # 当遍历序列的时候，元素的索引和值是可以同时遍历的，需要使用enumerate方法
    indices = []
    values = []

    for index, value in enumerate(['apple', 'banana', 'grape']):
        indices.append(index)
        values.append(value)

    print("index of sequence is {0} and element is {1}".format(indices, values))

    # 当同时遍历多个序列的时候，需要使用zip函数
    # 注意这是和其他语言不同的地方
    questions = ["name", "quest", "age"]
    answers = ["Alan", "the green grape", "22"]
    combinations = []

    for question, answer in zip(questions, answers):
        combinations.append("what is your {0}? It is {1}".format(question, answer))
    
    print("conbinations is {}".format(combinations))

def testRange():
    """
    range函数的使用
    range函数的返回对象很像是一个元组，但是实际上并不是；
    只是一个对象，在迭代时返回需要的连续项，并没有真正地产生list

    """
    print("list(range(5)) is {}".format(list(range(5))))

    print("list(range(1, 10)) is {}".format(list(range(1, 10))))

    print("list(range(1, 10, 3)) is {}".format(list(range(1, 10, 3))))

    print("list(range(-10, -100, -30)) is {}".format(list(range(-10, -100, -30))))

testFor()
testRange()